package handlers

import (
	"brood-agent2/controller"
	"brood-agent2/utils"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
)

type DockerInstaller struct {
	PkgUrl         DownloadUrl   `json:"pkg_url"`
	ApplicationDir string        `json:"application_dir"`
	DependFiles    []DownloadUrl `json:"depend_files"`
}

func InstallDockerHandler(rw http.ResponseWriter, req *http.Request) {
	res := &controller.JsonResponse{
		Code:    0,
		Data:    nil,
		Message: "success",
	}
	body, err := io.ReadAll(req.Body)
	if err != nil {
		controller.RenderJsonResponse(rw, &controller.JsonResponse{controller.CodeError, nil, fmt.Sprint(err)})
		return
	}

	var dockerInstaller DockerInstaller
	err = json.Unmarshal(body, &dockerInstaller)
	if err != nil {
		controller.RenderJsonResponse(rw, &controller.JsonResponse{controller.CodeError, nil, fmt.Sprint(err)})
		return
	}

	utils.Logger.Info(fmt.Sprintf("DockerInstaller: %+v", dockerInstaller))
	err = InstallDockerImpl(dockerInstaller)
	if err != nil {
		res.Code = controller.CodeError
		res.Message = fmt.Sprintf("%s", err)
	}

	controller.RenderJsonResponse(rw, res)
	return
}
